import tkinter as tk
import serial

# 设置串口通信
ser = serial.Serial('COM5', 9600)

def send_command(command):
    # 将命令转换为字节并发送到串口
    command_bytes = bytes.fromhex(command)
    ser.write(command_bytes)
    print(f"发送命令: {command}")

# 创建主窗口
root = tk.Tk()
root.title("摄像头控制")

# 创建按钮及其功能
def stop():
    send_command("81 01 06 01 18 18 03 03 FF")

def move_up():
    send_command("81 01 06 01 18 17 03 01 FF")

def move_down():
    send_command("81 01 06 01 18 17 03 02 FF")

def move_left():
    send_command("81 01 06 01 18 17 01 03 FF")

def move_right():
    send_command("81 01 06 01 18 17 02 03 FF")

def preset_set(number):
    command = f"81 01 04 3F 01 {number:02X} FF"
    send_command(command)

def recall_preset(number):
    command = f"81 01 04 3F 02 {number:02X} FF"
    send_command(command)

def zoom_in():
    send_command("81 01 04 07 24 FF")

def stop_zoom():
    send_command("81 01 04 07 00 FF")

def zoom_out():
    send_command("81 01 04 07 34 FF")

def query_position():
    send_command("81 09 06 12 FF")

# 创建按钮并布局
tk.Button(root, text="停止", command=stop).grid(row=0, column=1)
tk.Button(root, text="上", command=move_up).grid(row=1, column=1)
tk.Button(root, text="下", command=move_down).grid(row=3, column=1)
tk.Button(root, text="左", command=move_left).grid(row=2, column=0)
tk.Button(root, text="右", command=move_right).grid(row=2, column=2)

zoom_in_button = tk.Button(root, text="变焦远")
zoom_in_button.grid(row=4, column=0)
zoom_in_button.bind("<ButtonPress-1>", lambda event: zoom_in())
zoom_in_button.bind("<ButtonRelease-1>", lambda event: stop_zoom())

zoom_out_button = tk.Button(root, text="变焦近")
zoom_out_button.grid(row=4, column=2)
zoom_out_button.bind("<ButtonPress-1>", lambda event: zoom_out())
zoom_out_button.bind("<ButtonRelease-1>", lambda event: stop_zoom())

tk.Button(root, text="查询位置", command=query_position).grid(row=4, column=1)

for i in range(6):
    tk.Button(root, text=f"预置位设置 {i+1}", command=lambda i=i: preset_set(i)).grid(row=5+i, column=0)
    tk.Button(root, text=f"调用预置位 {i+1}", command=lambda i=i: recall_preset(i)).grid(row=5+i, column=2)

# 运行主循环
root.mainloop()

# 关闭串口
ser.close()
